<script lang="ts" setup generic="UserType extends IUser">
import { computed, ref, watch } from 'vue';

import type { IUser, UserAction } from '../../types';
import N8nActionToggle from '../N8nActionToggle';
import N8nLink from '../N8nLink';
import N8nLoading from '../N8nLoading';
import N8nText from '../N8nText';
import N8nTooltip from '../N8nTooltip';

export type PathItem = {
	id: string;
	label: string;
	href?: string;
};

type Props = {
	items: PathItem[];
	hiddenItems?: PathItem[] | Promise<PathItem[]>;
	theme?: 'small' | 'medium';
	showBorder?: boolean;
	loadingSkeletonRows?: number;
	separator?: string;
	highlightLastItem?: boolean;
	hiddenItemsTrigger?: 'hover' | 'click';
	// Setting this to true will show the ellipsis even if there are no hidden items
	pathTruncated?: boolean;
	dragActive?: boolean;
};

defineOptions({ name: 'N8nBreadcrumbs' });

const emit = defineEmits<{
	tooltipOpened: [];
	tooltipClosed: [];
	hiddenItemsLoadingError: [error: unknown];
	itemSelected: [item: PathItem];
	itemHover: [item: PathItem];
	itemDrop: [item: PathItem];
}>();

const props = withDefaults(defineProps<Props>(), {
	hiddenItems: () => new Array<PathItem>(),
	theme: 'medium',
	showBorder: false,
	loadingSkeletonRows: 3,
	separator: '/',
	highlightLastItem: true,
	pathTruncated: false,
	hiddenItemsTrigger: 'click',
	dragActive: false,
});

const loadedHiddenItems = ref<PathItem[]>([]);
const isLoadingHiddenItems = ref(false);
const currentPromise = ref<Promise<PathItem[]> | null>(null);

const hasHiddenItems = computed(() => {
	return Array.isArray(props.hiddenItems)
		? props.hiddenItems.length > 0
		: props.hiddenItems !== undefined;
});

const showEllipsis = computed(() => {
	return props.items.length && (hasHiddenItems.value || props.pathTruncated);
});

const dropdownDisabled = computed(() => {
	return props.pathTruncated && !hasHiddenItems.value;
});

const hiddenItemActions = computed((): Array<UserAction<UserType>> => {
	return loadedHiddenItems.value.map((item) => ({
		value: item.id,
		label: item.label,
		disabled: false,
	}));
});

const getHiddenItems = async () => {
	// If we already have items loaded and the source hasn't changed, use cache
	if (loadedHiddenItems.value.length > 0 && props.hiddenItems === currentPromise.value) {
		return;
	}

	// Handle synchronous array
	if (Array.isArray(props.hiddenItems)) {
		loadedHiddenItems.value = props.hiddenItems;
		return;
	}

	isLoadingHiddenItems.value = true;
	try {
		// Store the current promise for cache comparison
		currentPromise.value = props.hiddenItems;
		const items = await props.hiddenItems;
		loadedHiddenItems.value = items;
	} catch (error) {
		loadedHiddenItems.value = [];
		emit('hiddenItemsLoadingError', error);
	} finally {
		isLoadingHiddenItems.value = false;
	}
};

watch(
	(): PathItem[] | Promise<PathItem[]> => props.hiddenItems,
	(_newValue: PathItem[] | Promise<PathItem[]>) => {
		void getHiddenItems();
	},
);

const onHiddenMenuVisibleChange = async (visible: boolean) => {
	if (visible) {
		emit('tooltipOpened');
		await getHiddenItems();
	} else {
		emit('tooltipClosed');
	}
};

const emitItemSelected = (id: string) => {
	const item = [...props.items, ...loadedHiddenItems.value].find((i) => i.id === id);
	if (!item) {
		return;
	}
	emit('itemSelected', item);
};

const emitItemHover = (id: string) => {
	const item = [...props.items, ...loadedHiddenItems.value].find((i) => i.id === id);
	if (!item) {
		return;
	}
	emit('itemHover', item);
};

const onHiddenItemMouseUp = (item: UserAction<UserType>) => {
	const pathItem = [...props.items, ...loadedHiddenItems.value].find((i) => i.id === item.value);
	if (!pathItem || !props.dragActive) {
		return;
	}
	emit('itemDrop', pathItem);
};

const onItemMouseUp = (item: PathItem) => {
	if (!props.dragActive) {
		return;
	}
	emit('itemDrop', item);
};

const handleTooltipShow = async () => {
	emit('tooltipOpened');
	await getHiddenItems();
};

const handleTooltipClose = () => {
	emit('tooltipClosed');
};
</script>
<template>
	<div
		:class="{
			[$style.container]: true,
			[$style.border]: props.showBorder,
			[$style[props.theme]]: true,
			['n8n-breadcrumbs']: true,
		}"
	>
		<slot name="prepend"></slot>
		<ul :class="$style.list">
			<li v-if="$slots.prepend && items.length" :class="$style.separator">
				{{ separator }}
			</li>
			<li
				v-if="showEllipsis"
				:class="{ [$style.ellipsis]: true, [$style.disabled]: dropdownDisabled }"
				data-test-id="ellipsis"
			>
				<!-- Show interactive dropdown for larger versions -->
				<div v-if="props.theme !== 'small'" :class="$style['hidden-items-menu']">
					<N8nActionToggle
						:actions="hiddenItemActions"
						:loading="isLoadingHiddenItems"
						:loading-row-count="loadingSkeletonRows"
						:disabled="dropdownDisabled"
						:class="$style['action-toggle']"
						:popper-class="`${$style['hidden-items-menu-popper']} ${dragActive ? $style.dragging : ''}`"
						:trigger="hiddenItemsTrigger"
						theme="dark"
						placement="bottom"
						size="small"
						icon-orientation="horizontal"
						data-test-id="hidden-items-menu"
						@visible-change="onHiddenMenuVisibleChange"
						@action="emitItemSelected"
						@item-mouseup="onHiddenItemMouseUp"
					>
						<N8nText :bold="true" :class="$style.dots">...</N8nText>
					</N8nActionToggle>
				</div>
				<!-- Just a tooltip for smaller versions -->
				<N8nTooltip
					v-else
					:popper-class="$style.tooltip"
					:disabled="dropdownDisabled"
					:trigger="hiddenItemsTrigger"
					placement="bottom"
					@before-show="handleTooltipShow"
					@hide="handleTooltipClose"
				>
					<template #content>
						<div v-if="isLoadingHiddenItems" :class="$style['tooltip-loading']">
							<N8nLoading
								:rows="1"
								:loading="isLoadingHiddenItems"
								animated
								variant="p"
								:shrink-last="false"
							/>
						</div>
						<div v-else :class="$style.tooltipContent">
							<div data-test-id="hidden-items-tooltip">
								<N8nText>{{ loadedHiddenItems.map((item) => item.label).join(' / ') }}</N8nText>
							</div>
						</div>
					</template>
					<span :class="$style['tooltip-ellipsis']">...</span>
				</N8nTooltip>
			</li>
			<li v-if="showEllipsis" :class="$style.separator">{{ separator }}</li>
			<template v-for="(item, index) in items" :key="item.id">
				<li
					:class="{
						[$style.item]: true,
						[$style.current]: props.highlightLastItem && index === items.length - 1,
						[$style.dragging]: props.dragActive,
					}"
					:title="item.label"
					:data-resourceid="item.id"
					data-test-id="breadcrumbs-item"
					data-target="folder-breadcrumb-item"
					@click.prevent="emitItemSelected(item.id)"
					@mouseenter="emitItemHover(item.id)"
					@mouseup="onItemMouseUp(item)"
				>
					<N8nLink v-if="item.href" :href="item.href" theme="text">{{ item.label }}</N8nLink>
					<N8nText v-else>{{ item.label }}</N8nText>
				</li>
				<li v-if="index !== items.length - 1" :class="$style.separator">
					{{ separator }}
				</li>
			</template>
		</ul>
		<slot name="append"></slot>
	</div>
</template>
<style lang="scss" module>
.container {
	display: flex;
	align-items: center;

	&.small {
		display: inline-flex;
		padding: var(--spacing--4xs) var(--spacing--3xs);
	}

	&.border {
		border: var(--border);
		border-radius: var(--radius);
	}
}

.list {
	display: flex;
	list-style: none;
	align-items: center;
}

.item {
	border: var(--border-width) var(--border-style) transparent;
}

.item.dragging:hover {
	border: var(--border-width) var(--border-style) var(--color--secondary);
	border-radius: var(--radius);
	background-color: var(--callout--color--background--secondary);

	& a {
		cursor: grabbing;
	}
}

.item * {
	display: block;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
}

.item.current span {
	color: var(--color--text--shade-1);
}

// Make disabled ellipsis look like a normal item
.ellipsis {
	.dots,
	.tooltip-ellipsis {
		cursor: pointer;
		user-select: none;
		color: var(--color--text);
	}
	&.disabled {
		.dots,
		.tooltip-ellipsis {
			cursor: default;
		}
		.dots {
			cursor: default;
			color: var(--color--text);
			&:hover {
				color: var(--color--text);
			}
		}
	}
}

.hidden-items-menu {
	display: flex;
	color: var(--color--text);
}

.hidden-items-menu-popper {
	& > div ul {
		max-height: 250px;
		overflow: auto;
	}

	&.dragging li:hover {
		cursor: grabbing;
		background-color: var(--callout--color--background--secondary);
	}

	li {
		max-width: var(--spacing--5xl);
		display: block;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}
}

.tooltip-loading {
	min-width: var(--spacing--3xl);
	width: 100%;

	:global(.n8n-loading) > div {
		display: flex;
		flex-direction: column;
		gap: var(--spacing--xs);
	}

	:global(.el-skeleton__item) {
		margin: 0;
	}
}

.tooltip {
	padding: var(--spacing--xs) var(--spacing--2xs);
	text-align: center;
	& > div {
		color: var(--color--text--tint-2);
		span {
			font-size: var(--font-size--2xs);
		}
	}

	.tooltip-loading {
		min-width: var(--spacing--4xl);
	}
}

.dots {
	padding: 0 var(--spacing--4xs);
	color: var(--color--text--tint-1);
	border-radius: var(--radius);

	&:hover,
	&:focus {
		background-color: var(--color--background);
		color: var(--color--primary);
	}
}

// Small theme overrides
.small {
	.list {
		gap: var(--spacing--5xs);
	}

	.item {
		max-width: var(--spacing--3xl);
	}

	.item,
	.item * {
		color: var(--color--text);
		font-size: var(--font-size--2xs);
		line-height: var(--line-height--xs);
	}

	.item a:hover * {
		color: var(--color--text--shade-1);
	}

	.separator {
		font-size: var(--font-size--sm);
		color: var(--color--text);
	}
}

// Medium theme overrides
.medium {
	li {
		padding: var(--spacing--3xs) var(--spacing--4xs) var(--spacing--4xs);
	}

	.item,
	.item * {
		color: var(--color--text);
		font-size: var(--font-size--sm);
		line-height: var(--line-height--xs);
	}

	.item {
		max-width: var(--spacing--5xl);
	}

	.item:not(.dragging) a:hover * {
		color: var(--color--text--shade-1);
	}

	.ellipsis {
		padding-right: 0;
		padding-left: 0;
		color: var(--color--text--tint-1);
		&:hover {
			color: var(--color--text);
		}
	}

	.separator {
		font-size: var(--font-size--xl);
		color: var(--color--foreground);
	}
}
</style>
